﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BlogManager.Core.BaseArchitecture;
using BlogManager.Data.Entities;

namespace BlogManager.Application
{
    public partial class Domain : AppFormBase
    {
        private int? _id;

        public override void PageLoad()
        {
            base.PageLoad();
            if(!string.IsNullOrEmpty(Request.QueryString["Id"]))
                _id=Convert.ToInt32(Request.QueryString["Id"]);
        }

        public override void PageDataLoad()
        {
            if(_id!=null)
            {
                var site = Data.Entities.Site.SingleOrDefault(x => x.Id == _id.Value);

                if(site!=null)
                {
                    TextBoxForUrl.Text = site.Url;
                    TextBoxForFTPUserName.Text = site.FTPUser;
                    TextBoxForFTPPassword.Text = site.FTPPassword;

                    ButtonForDeleting.Visible = true;
                }
            }
        }

        protected void ButtonForSaving_Click(object sender, EventArgs e)
        {
            Save();
        }

        protected void ButtonForSaveAndNew_Click(object sender, EventArgs e)
        {
            Save();
            MessagesForActions.Redirect(ResolveClientUrl(AppRelativeVirtualPath));
        }

        public override void Save()
        {
            Site site = _id != null ? Data.Entities.Site.SingleOrDefault(x => x.Id == _id.Value) : new Data.Entities.Site();

            site.Url = TextBoxForUrl.Text;
            site.FTPUser = TextBoxForFTPUserName.Text;
            site.FTPPassword = TextBoxForFTPPassword.Text;

            try
            {
                site.Save();
                MessagesForActions.Show = true;
                MessagesForActions.Message = "Saved!";
            }
            catch (Exception ex)
            {
                MessagesForActions.Show = true;
                MessagesForActions.Message = "Error!";
            }
        }

        protected void ButtonForDeleting_Click(object sender, EventArgs e)
        {
            if(_id==null)
                return;            

            try
            {
                Data.Entities.Site.Delete(x => x.Id == _id.Value);
            }
            catch (Exception ex)
            {
                MessagesForActions.Show = true;
                MessagesForActions.Message = "Error!";
            }


            TextBoxForUrl.Text = "";
            TextBoxForFTPPassword.Text = "";
            TextBoxForFTPUserName.Text = "";
        }


        public override void Delete()
        {
            
        }
    }
}